package com.jctrip.hotel.source.service.atour.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jctrip.hotel.domain.dao.HtSourceInfoDao;
import com.jctrip.hotel.domain.entity.HtSourceInfo;
import com.jctrip.hotel.source.service.HotelCommonTaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jctrip.hotel.common.enums.OrderStatusEnum;
import com.jctrip.hotel.common.enums.SourceEnum;
import com.jctrip.hotel.common.util.JsonUtil;
import com.jctrip.hotel.source.client.AtourClient;
import com.jctrip.hotel.source.model.OrderDataResult;
import com.jctrip.hotel.source.model.PriceCheckParam;
import com.jctrip.hotel.source.model.atour.req.CancelOrderReq;
import com.jctrip.hotel.source.model.atour.req.CreateOrderReq;
import com.jctrip.hotel.source.model.atour.req.CreateOrderReq.RoomRate;
import com.jctrip.hotel.source.model.atour.req.QueryOrderReq;
import com.jctrip.hotel.source.model.atour.req.QueryOrderResp;
import com.jctrip.hotel.source.model.atour.resp.AtourResult;
import com.jctrip.hotel.source.model.atour.resp.CancelOrderResp;
import com.jctrip.hotel.source.model.atour.resp.CityData;
import com.jctrip.hotel.source.model.atour.resp.CreateOrderResp;
import com.jctrip.hotel.source.model.atour.resp.HotelData;
import com.jctrip.hotel.source.model.atour.resp.RoomInventoryData;
import com.jctrip.hotel.source.model.atour.resp.RoomRateData;
import com.jctrip.hotel.source.model.atour.resp.RoomTypeData;
import com.jctrip.hotel.source.model.wehotel.req.OrderData;
import com.jctrip.hotel.source.service.atour.AtourService;
import com.jctrip.hotel.source.service.atour.AtourSignUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author henry
 * @Date 2023/6/3 15:16
 * @Description
 */
@Component
@Slf4j
public class AtourServiceImpl implements AtourService {
    @Resource
    private AtourClient atourClient;

    @Resource
    private HtSourceInfoDao htSourceInfoDao;

    @Autowired
    private HotelCommonTaskService hotelCommonTaskService;

    @Override
    public Integer parseAppId(String appId) {
        if (StringUtils.isBlank(appId)) {
            return null;
        }

        return Integer.valueOf(appId);
    }

    @Override
    public Integer parseHotelId(String innId) {
        if (StringUtils.isBlank(innId)) {
            return null;
        }

        return Integer.valueOf(innId.substring(SourceEnum.ATOUR.getCode().length()));
    }

    @Override
    public String parseInnId(Integer hotelId) {
        if (null == hotelId) {
            return null;
        }

        return SourceEnum.ATOUR.getCode() + hotelId;
    }

    @Override
    public Integer parseRoomTypeId(String roomTypeCode) {
        if (StringUtils.isBlank(roomTypeCode)) {
            return null;
        }

        return Integer.valueOf(roomTypeCode);
    }

    @Override
    public List<CityData> getCityList(Integer appId, String key) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", String.valueOf(appId));
        Long timestamp = System.currentTimeMillis();
        paramMap.put("timestamp", String.valueOf(timestamp));

        List<CityData> cityDataList = new ArrayList<>();
        String sign = AtourSignUtils.genSign(key, paramMap);
        AtourResult<List<CityData>> atourResult = atourClient.getCityList(appId, sign, timestamp);
        if (null == atourResult) {
            return cityDataList;
        }

        if (1000 != atourResult.getLevel()) {
            throw new RuntimeException(atourResult.getMsg());
        }

        cityDataList = atourResult.getResult();

        return cityDataList;
    }

    @Override
    public List<HotelData> getHotelList(Integer appId, String key, Integer cityId) {
        if (null == cityId) {
            throw new RuntimeException("城市ID为空");
        }

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", String.valueOf(appId));
        paramMap.put("cityId", String.valueOf(cityId));
        Long timestamp = System.currentTimeMillis();
        paramMap.put("timestamp", String.valueOf(timestamp));

        List<HotelData> hotelDataList = new ArrayList<>();

        String sign = AtourSignUtils.genSign(key, paramMap);
        AtourResult<List<HotelData>> atourResult = atourClient.getHotelList(appId, cityId, sign, timestamp);

        if (null == atourResult) {
            return hotelDataList;
        }

        if (1000 != atourResult.getLevel()) {
            throw new RuntimeException(atourResult.getMsg());
        }

        hotelDataList = atourResult.getResult();

        return hotelDataList;
    }

    @Override
    public HotelData getHotel(Integer appId, String key, Integer hotelId) {
        if (null == hotelId) {
            throw new RuntimeException("酒店ID为空");
        }

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", String.valueOf(appId));
        paramMap.put("hotelId", String.valueOf(hotelId));
        Long timestamp = System.currentTimeMillis();
        paramMap.put("timestamp", String.valueOf(timestamp));

        HotelData hotelData = null;

        String sign = AtourSignUtils.genSign(key, paramMap);
        AtourResult<HotelData> atourResult = atourClient.getHotel(appId, hotelId, sign, timestamp);

        if (null == atourResult) {
            return hotelData;
        }

        if (1000 != atourResult.getLevel()) {
            throw new RuntimeException(atourResult.getMsg());
        }

        hotelData = atourResult.getResult();

        return hotelData;
    }

    @Override
    public List<RoomTypeData> getRoomTypeList(Integer appId, String key, Integer hotelId) {
        if (null == hotelId) {
            throw new RuntimeException("酒店ID为空");
        }

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", String.valueOf(appId));
        paramMap.put("hotelId", String.valueOf(hotelId));
        Long timestamp = System.currentTimeMillis();
        paramMap.put("timestamp", String.valueOf(timestamp));

        List<RoomTypeData> roomTypeDataList = new ArrayList<>();

        String sign = AtourSignUtils.genSign(key, paramMap);

        AtourResult<List<RoomTypeData>> atourResult = atourClient.getRoomTypeList(appId, hotelId, sign, timestamp);

        if (null == atourResult) {
            return roomTypeDataList;
        }

        if (1000 != atourResult.getLevel()) {
            throw new RuntimeException(atourResult.getMsg());
        }

        roomTypeDataList = atourResult.getResult();

        return roomTypeDataList;
    }

    @Override
    public List<RoomRateData> getRoomRateList(Integer appId, String key, Integer hotelId, Integer roomTypeId,
            String start, String end, Integer roomRateTypeId, Integer mebId) {
        if (null == hotelId) {
            throw new RuntimeException("酒店ID为空");
        }

        if (StringUtils.isBlank(start)) {
            throw new RuntimeException("开始日期为空");
        }

        if (StringUtils.isBlank(end)) {
            throw new RuntimeException("结束日期为空");
        }

        if (null == mebId) {
            throw new RuntimeException("会员ID为空");
        }

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", String.valueOf(appId));
        paramMap.put("hotelId", String.valueOf(hotelId));
        if (null != roomTypeId) {
            paramMap.put("roomTypeId", String.valueOf(roomTypeId));
        }
        paramMap.put("start", start);
        paramMap.put("end", end);
        if (null != roomRateTypeId) {
            paramMap.put("roomRateTypeId", String.valueOf(roomRateTypeId));
        }
        paramMap.put("mebId", String.valueOf(mebId));
        Long timestamp = System.currentTimeMillis();
        paramMap.put("timestamp", String.valueOf(timestamp));

        List<RoomRateData> roomRateDataList = new ArrayList<>();

        String sign = AtourSignUtils.genSign(key, paramMap);
        AtourResult<List<RoomRateData>> atourResult =
                atourClient.getRoomRateList(appId, hotelId, roomTypeId, start, end, roomRateTypeId, mebId, sign,
                        timestamp);

        if (null == atourResult) {
            return roomRateDataList;
        }

        if (1000 != atourResult.getLevel()) {
            throw new RuntimeException(atourResult.getMsg());
        }

        roomRateDataList = atourResult.getResult();

        return roomRateDataList;
    }

    @Override
    public List<RoomInventoryData> getRoomInventoryList(Integer appId, String key, Integer hotelId, Integer roomTypeId,
            String start, String end, Integer roomRateTypeId, Integer mebId) {
        if (null == hotelId) {
            throw new RuntimeException("酒店ID为空");
        }

        if (StringUtils.isBlank(start)) {
            throw new RuntimeException("开始日期为空");
        }

        if (StringUtils.isBlank(end)) {
            throw new RuntimeException("结束日期为空");
        }

        if (null == mebId) {
            throw new RuntimeException("会员ID为空");
        }

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", String.valueOf(appId));
        paramMap.put("hotelId", String.valueOf(hotelId));
        if (null != roomTypeId) {
            paramMap.put("roomTypeId", String.valueOf(roomTypeId));
        }
        paramMap.put("start", start);
        paramMap.put("end", end);
        if (null != roomRateTypeId) {
            paramMap.put("roomRateTypeId", String.valueOf(roomRateTypeId));
        }
        paramMap.put("mebId", String.valueOf(mebId));
        Long timestamp = System.currentTimeMillis();
        paramMap.put("timestamp", String.valueOf(timestamp));

        List<RoomInventoryData> roomInventoryDataList = new ArrayList<>();

        String sign = AtourSignUtils.genSign(key, paramMap);
        AtourResult<List<RoomInventoryData>> atourResult =
                atourClient.getRoomInventoryList(appId, hotelId, roomTypeId, start, end, roomRateTypeId, mebId, sign,
                        timestamp);

        if (null == atourResult) {
            return roomInventoryDataList;
        }

        if (1000 != atourResult.getLevel()) {
            throw new RuntimeException(atourResult.getMsg());
        }

        roomInventoryDataList = atourResult.getResult();

        return roomInventoryDataList;
    }

    @Override
    public List<CreateOrderReq.RoomRate> roomRateList(Integer appId, String key, Integer hotelId,
            Integer roomTypeId, String start, String end, Integer roomRateTypeId, Integer mebId) {
        List<RoomRateData> roomRateDataList =
                getRoomRateList(appId, key, hotelId, roomTypeId, start, end, roomRateTypeId, mebId);
        List<CreateOrderReq.RoomRate> roomRateList = new ArrayList<>();
        Optional.of(roomRateDataList).orElseThrow(() -> new RuntimeException("获取房价信息失败"))
                .forEach(roomRateData -> {
                    CreateOrderReq.RoomRate roomRate = new CreateOrderReq.RoomRate();
                    roomRate.setAccDate(roomRateData.getAccDate());
                    roomRate.setRoomRate(roomRateData.getRoomRate());
                    roomRateList.add(roomRate);
                });
        return roomRateList;
    }

    @Override
    public OrderDataResult postOrder(Integer appId, String key, CreateOrderReq createOrderReq,
            PriceCheckParam priceCheck, String sourceExtra) {
        if (null == createOrderReq) {
            throw new RuntimeException("参数为空");
        }

        if (null == createOrderReq.getHotelId()) {
            throw new RuntimeException("酒店ID为空");
        }

        if (null == createOrderReq.getRoomTypeId()) {
            throw new RuntimeException("酒店房间类型ID为空");
        }

        if (null == createOrderReq.getRoomNum()) {
            throw new RuntimeException("酒店房间数量为空");
        }

        if (null == createOrderReq.getRoomRateTypeId()) {
            throw new RuntimeException("酒店房间价格类型ID为空");
        }

        BigDecimal rate = BigDecimal.ONE;
        String discountRate = (String) JsonUtil.toMap(sourceExtra).get("discountRate");
        if (StringUtils.isNotBlank(discountRate)) {
            rate = rate.subtract(new BigDecimal(discountRate));
        }

        // 查询实时房态
        List<RoomRate> roomRateList =
                roomRateList(appId, key, createOrderReq.getHotelId(), createOrderReq.getRoomTypeId(),
                        createOrderReq.getArrival(), createOrderReq.getDeparture(), createOrderReq.getRoomRateTypeId(),
                        createOrderReq.getMebId());

        BigDecimal raisedTotalPrice = BigDecimal.valueOf(0);
        BigDecimal atourTotalRate = BigDecimal.ZERO;
        List<RoomRate> roomRateListReq = new ArrayList<>();
        for (RoomRate roomRate : roomRateList) {
            if (!roomRate.getAccDate().equals(createOrderReq.getDeparture())) {
                raisedTotalPrice = raisedTotalPrice.add(
                        priceCheck.getRaiseFunc().apply(BigDecimal.valueOf(roomRate.getRoomRate())));
                atourTotalRate = atourTotalRate.add(BigDecimal.valueOf(roomRate.getRoomRate()));
                roomRateListReq.add(roomRate);
            }
        }
        // todo 临时去除价格还原
//        if (priceCheck.getTotalRate().compareTo(raisedTotalPrice.multiply(BigDecimal.valueOf(createOrderReq.getRoomNum()))
//                .subtract(priceCheck.getTolerancePrice())) < 0) {
//            log.error("订单销售价不能低于采购总价，订单销售价={}，采购总价={}, 容差金额={}",
//                    priceCheck.getTotalRate(), raisedTotalPrice, priceCheck.getTolerancePrice());
//            throw new RuntimeException("订单销售价不能低于采购总价");
//        }
        if (priceCheck.getTotalRate().multiply(rate).compareTo(atourTotalRate.multiply(BigDecimal.valueOf(createOrderReq.getRoomNum()))
                .subtract(priceCheck.getTolerancePrice())) < 0) {
            String error = String.format("订单销售价不能低于采购总价，订单销售价=%s，采购总价=%s, 容差金额=%s, 目前差额=%s",
                    priceCheck.getTotalRate(),
                    atourTotalRate.multiply(BigDecimal.valueOf(createOrderReq.getRoomNum())),
                    priceCheck.getTolerancePrice(),
                    atourTotalRate.multiply(BigDecimal.valueOf(createOrderReq.getRoomNum())).subtract(priceCheck.getTotalRate()));
            hotelCommonTaskService.insertOrderErrorLog(createOrderReq.getThirdOrderNo(),
                    JsonUtil.toString(createOrderReq), error);
            log.error("订单销售价不能低于采购总价，订单销售价={}，采购总价={}, 容差金额={}, 目前差额={}",
                    priceCheck.getTotalRate(), atourTotalRate.multiply(BigDecimal.valueOf(createOrderReq.getRoomNum())),
                    priceCheck.getTolerancePrice(), atourTotalRate.multiply(BigDecimal.valueOf(createOrderReq.getRoomNum())).subtract(priceCheck.getTotalRate()));
            throw new RuntimeException("订单销售价不能低于采购总价");
        }
        createOrderReq.setRoomRateList(JsonUtil.toString(roomRateListReq));

        // todo
        //
        //        String remark = "房费统一与亚朵集团月结，请勿收取客人费用，房价保密，杂费自理，发票请勿开给住店客人。此单请勿延住。";
        //        createOrderReq.setRemark(remark + createOrderReq.getRemark());
        createOrderReq.setRemark(null);

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", String.valueOf(appId));
        paramMap.put("hotelId", String.valueOf(createOrderReq.getHotelId()));
        paramMap.put("roomTypeId", String.valueOf(createOrderReq.getRoomTypeId()));
        paramMap.put("roomNum", String.valueOf(createOrderReq.getRoomNum()));
        paramMap.put("roomRateTypeId", String.valueOf(createOrderReq.getRoomRateTypeId()));
        paramMap.put("roomRateList", createOrderReq.getRoomRateList());
        paramMap.put("arrival", createOrderReq.getArrival());
        if (null != createOrderReq.getAssureTime()) {
            paramMap.put("assureTime", String.valueOf(createOrderReq.getAssureTime()));
        }
        paramMap.put("departure", createOrderReq.getDeparture());
        paramMap.put("mobile", createOrderReq.getMobile());
        paramMap.put("contactName", createOrderReq.getContactName());
        paramMap.put("guestName", createOrderReq.getGuestName());
        paramMap.put("source", String.valueOf(createOrderReq.getSource()));
        paramMap.put("subSource", String.valueOf(createOrderReq.getSubSource()));
        paramMap.put("thirdOrderNo", createOrderReq.getThirdOrderNo());
        if (StringUtils.isNotBlank(createOrderReq.getCouponsList())) {
            paramMap.put("couponsList", createOrderReq.getCouponsList());
        }
        if (StringUtils.isNotBlank(createOrderReq.getRemark())) {
            paramMap.put("remark", createOrderReq.getRemark());
        }
        paramMap.put("mebId", String.valueOf(createOrderReq.getMebId()));
        Long timestamp = System.currentTimeMillis();
        paramMap.put("timestamp", String.valueOf(timestamp));

        String sign = AtourSignUtils.genSign(key, paramMap);

        createOrderReq.setSign(sign);
        createOrderReq.setTimestamp(timestamp);

        AtourResult<CreateOrderResp> atourResult = atourClient.createOrder(createOrderReq);
        if (null == atourResult) {
            return null;
        }

        if (1000 != atourResult.getLevel()) {
            hotelCommonTaskService.insertOrderErrorLog(createOrderReq.getThirdOrderNo(),
                    JsonUtil.toString(createOrderReq), atourResult.getMsg());
            throw new RuntimeException(atourResult.getMsg());
        }
        CreateOrderResp result = atourResult.getResult();
        return OrderDataResult.builder().orderCode(result.getAtourOrderNo())
                .externalId(createOrderReq.getThirdOrderNo()).totalRate(atourTotalRate.multiply(BigDecimal.valueOf(createOrderReq.getRoomNum()))).orderState(
                        OrderStatusEnum.BOOK_SUCCESS.getCode()).responseJsonStr(JsonUtil.toString(atourResult))
                .requestJsonStr(JsonUtil.toString(createOrderReq)).build();
    }

    @Override
    public CreateOrderResp creatOrder(Integer appId, String key, CreateOrderReq createOrderReq) {
        if (null == createOrderReq) {
            throw new RuntimeException("参数为空");
        }

        if (null == createOrderReq.getHotelId()) {
            throw new RuntimeException("酒店ID为空");
        }

        if (null == createOrderReq.getRoomTypeId()) {
            throw new RuntimeException("酒店房间类型ID为空");
        }

        if (null == createOrderReq.getRoomNum()) {
            throw new RuntimeException("酒店房间数量为空");
        }

        if (null == createOrderReq.getRoomRateTypeId()) {
            throw new RuntimeException("酒店房间价格类型ID为空");
        }


        // 查询实时房态
        List<RoomRate> roomRateList =
                roomRateList(appId, key, createOrderReq.getHotelId(), createOrderReq.getRoomTypeId(),
                        createOrderReq.getArrival(), createOrderReq.getDeparture(), createOrderReq.getRoomRateTypeId(),
                        createOrderReq.getMebId());
        List<RoomRate> roomRateListReq = new ArrayList<>();

        for (RoomRate roomRate : roomRateList) {
            if (!roomRate.getAccDate().equals(createOrderReq.getDeparture())) {
                roomRateListReq.add(roomRate);
            }
        }

        createOrderReq.setRoomRateList(JsonUtil.toString(roomRateListReq));

        // todo
        //
        //        String remark = "房费统一与亚朵集团月结，请勿收取客人费用，房价保密，杂费自理，发票请勿开给住店客人。此单请勿延住。";
        //        createOrderReq.setRemark(remark + createOrderReq.getRemark());
        createOrderReq.setRemark(null);

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", String.valueOf(appId));
        paramMap.put("hotelId", String.valueOf(createOrderReq.getHotelId()));
        paramMap.put("roomTypeId", String.valueOf(createOrderReq.getRoomTypeId()));
        paramMap.put("roomNum", String.valueOf(createOrderReq.getRoomNum()));
        paramMap.put("roomRateTypeId", String.valueOf(createOrderReq.getRoomRateTypeId()));
        paramMap.put("roomRateList", createOrderReq.getRoomRateList());
        paramMap.put("arrival", createOrderReq.getArrival());
        if (null != createOrderReq.getAssureTime()) {
            paramMap.put("assureTime", String.valueOf(createOrderReq.getAssureTime()));
        }
        paramMap.put("departure", createOrderReq.getDeparture());
        paramMap.put("mobile", createOrderReq.getMobile());
        paramMap.put("contactName", createOrderReq.getContactName());
        paramMap.put("guestName", createOrderReq.getGuestName());
        paramMap.put("source", String.valueOf(createOrderReq.getSource()));
        paramMap.put("subSource", String.valueOf(createOrderReq.getSubSource()));
        paramMap.put("thirdOrderNo", createOrderReq.getThirdOrderNo());
        if (StringUtils.isNotBlank(createOrderReq.getCouponsList())) {
            paramMap.put("couponsList", createOrderReq.getCouponsList());
        }
        if (StringUtils.isNotBlank(createOrderReq.getRemark())) {
            paramMap.put("remark", createOrderReq.getRemark());
        }
        paramMap.put("mebId", String.valueOf(createOrderReq.getMebId()));
        Long timestamp = System.currentTimeMillis();
        paramMap.put("timestamp", String.valueOf(timestamp));

        String sign = AtourSignUtils.genSign(key, paramMap);

        createOrderReq.setSign(sign);
        createOrderReq.setTimestamp(timestamp);

        AtourResult<CreateOrderResp> atourResult = atourClient.createOrder(createOrderReq);
        if (null == atourResult) {
            return null;
        }

        if (1000 != atourResult.getLevel()) {
            throw new RuntimeException(atourResult.getMsg());
        }
        CreateOrderResp result = atourResult.getResult();

        return result;
    }

    @Override
    public OrderData queryOrderData(Integer appId, String key, String orderNo, String outOrderNo) {
        QueryOrderReq req = QueryOrderReq.builder().atourOrderNo(orderNo).orderNo(outOrderNo).appId(appId).build();
        QueryOrderResp queryOrderResp = queryOrder(appId, key, req);
        OrderData result = new OrderData();
        result.setOrderCode(orderNo);
        result.setExternalId(outOrderNo);
        result.setOrderState(queryOrderResp.getStatus());
        return result;
    }

    @Override
    public QueryOrderResp queryOrder(Integer appId, String key, QueryOrderReq queryOrderReq) {
        if (null == queryOrderReq) {
            throw new RuntimeException("参数为空");
        }

        if (StringUtils.isBlank(queryOrderReq.getOrderNo())) {
            throw new RuntimeException("第三方订单号为空");
        }

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", String.valueOf(appId));
        paramMap.put("orderNo", queryOrderReq.getOrderNo());
        if (StringUtils.isNotBlank(queryOrderReq.getAtourOrderNo())) {
            paramMap.put("atourOrderNo", queryOrderReq.getAtourOrderNo());
        }
        Long timestamp = System.currentTimeMillis();
        paramMap.put("timestamp", String.valueOf(timestamp));

        String sign = AtourSignUtils.genSign(key, paramMap);
        queryOrderReq.setSign(sign);
        queryOrderReq.setTimestamp(timestamp);

        QueryOrderResp queryOrderResp = null;

        AtourResult<List<QueryOrderResp>> atourResult = atourClient.queryOrder(queryOrderReq);

        if (null == atourResult) {
            throw new RuntimeException("查询结果为空");
        }

        if (1000 != atourResult.getLevel()) {
            throw new RuntimeException(atourResult.getMsg());
        }

        if (CollectionUtils.isNotEmpty(atourResult.getResult())) {
            queryOrderResp = atourResult.getResult().get(0);
        }

        return queryOrderResp;
    }

    @Override
    public QueryOrderResp queryDirectOrder(String sourceId, QueryOrderReq queryOrderReq) {
        if (null == queryOrderReq) {
            throw new RuntimeException("参数为空");
        }

        if (StringUtils.isBlank(queryOrderReq.getOrderNo())) {
            throw new RuntimeException("第三方订单号为空");
        }
        HtSourceInfo htSourceInfo =
                htSourceInfoDao.selectOne(new LambdaQueryWrapper<HtSourceInfo>().eq(HtSourceInfo::getSourceId,
                        sourceId));
        if (htSourceInfo == null) {
            throw new RuntimeException("供应商账户为空");
        }
        String appId = htSourceInfo.getSourceAppId();
        String key = htSourceInfo.getSourceSecret();


        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", String.valueOf(appId));
        paramMap.put("orderNo", queryOrderReq.getOrderNo());
        if (StringUtils.isNotBlank(queryOrderReq.getAtourOrderNo())) {
            paramMap.put("atourOrderNo", queryOrderReq.getAtourOrderNo());
        }
        Long timestamp = System.currentTimeMillis();
        paramMap.put("timestamp", String.valueOf(timestamp));

        String sign = AtourSignUtils.genSign(key, paramMap);
        queryOrderReq.setAppId(Integer.parseInt(appId));
        queryOrderReq.setSign(sign);
        queryOrderReq.setTimestamp(timestamp);

        QueryOrderResp queryOrderResp = null;

        AtourResult<List<QueryOrderResp>> atourResult = atourClient.queryOrder(queryOrderReq);

        if (null == atourResult) {
            throw new RuntimeException("查询结果为空");
        }

        if (1000 != atourResult.getLevel()) {
            throw new RuntimeException(atourResult.getMsg());
        }

        if (CollectionUtils.isNotEmpty(atourResult.getResult())) {
            queryOrderResp = atourResult.getResult().get(0);
        }

        return queryOrderResp;
    }


    @Override
    public CancelOrderResp cancelOrder(Integer appId, String key, CancelOrderReq cancelOrderReq) {
        if (null == cancelOrderReq) {
            throw new RuntimeException("参数为空");
        }

        if (StringUtils.isBlank(cancelOrderReq.getAtourOrderNo())) {
            throw new RuntimeException("亚朵订单号为空");
        }

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appId", String.valueOf(appId));
        if (StringUtils.isNotBlank(cancelOrderReq.getOrderNo())) {
            paramMap.put("orderNo", cancelOrderReq.getOrderNo());
        }
        paramMap.put("atourOrderNo", cancelOrderReq.getAtourOrderNo());
        Long timestamp = System.currentTimeMillis();
        paramMap.put("timestamp", String.valueOf(timestamp));

        String sign = AtourSignUtils.genSign(key, paramMap);
        cancelOrderReq.setSign(sign);
        cancelOrderReq.setTimestamp(timestamp);

        CancelOrderResp cancelOrderResp = null;

        AtourResult<CancelOrderResp> atourResult = atourClient.cancelOrder(cancelOrderReq);

        if (null == atourResult) {
            return cancelOrderResp;
        }

        if (1000 != atourResult.getLevel()) {
            throw new RuntimeException(atourResult.getMsg());
        }

        cancelOrderResp = atourResult.getResult();

        return cancelOrderResp;
    }

}